<?php

namespace App\Services;

use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Product;
use App\Models\ProductVariant;
use App\Models\UserAddress;
use App\Models\UserCoupon;
use App\Services\OrderNumberGenerator;
use App\Services\StockService;
use App\Services\CouponService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 订单服务类
 * 
 * 负责处理订单相关的所有业务逻辑，包括：
 * - 订单创建（立即购买和购物车）
 * - 支付处理
 * - 订单状态管理
 * - 订单查询和详情获取
 * - 订单取消和确认收货
 * 
 * @package App\Services
 * @author AI Assistant
 * @version 1.0.0
 */
class OrderService
{
    /**
     * 库存服务
     * 
     * @var StockService
     */
    protected StockService $stockService;
    
    /**
     * 订单号生成器
     * 
     * @var OrderNumberGenerator
     */
    protected OrderNumberGenerator $orderNumberGenerator;
    
    /**
     * 优惠券服务
     * 
     * @var CouponService
     */
    protected CouponService $couponService;

    /**
     * 构造函数
     * 
     * @param StockService $stockService 库存服务
     * @param OrderNumberGenerator $orderNumberGenerator 订单号生成器
     * @param CouponService $couponService 优惠券服务
     */
    public function __construct(StockService $stockService, OrderNumberGenerator $orderNumberGenerator, CouponService $couponService)
    {
        $this->stockService = $stockService;
        $this->orderNumberGenerator = $orderNumberGenerator;
        $this->couponService = $couponService;
    }

    /**
     * 从立即购买创建订单
     * 
     * @param array $item 商品信息，包含product_id, variant_id, quantity等
     * @param array $summary 订单汇总信息，包含total, subtotal, shipping, discount等
     * @param UserAddress $address 收货地址
     * @param array $requestData 请求数据，包含notes等
     * @return Order 创建的订单实例
     * @throws \Exception 当库存不足或创建失败时抛出异常
     */
    public function createFromBuyNow(array $item, array $summary, UserAddress $address, array $requestData): Order
    {
        return DB::transaction(function () use ($item, $summary, $address, $requestData) {
            // 获取优惠券ID和折扣金额
            $userCouponId = $requestData['user_coupon_id'] ?? null;
            $couponDiscount = isset($summary['coupon_discount']) ? $summary['coupon_discount'] : 0;

            // 创建订单
            $order = Order::create([
                'user_id' => auth()->id(),
                'order_number' => $this->orderNumberGenerator->generate(),
                'total_amount' => $summary['total'],
                'subtotal_amount' => $summary['subtotal'],
                'shipping_fee' => $summary['shipping'],
                'discount_amount' => $summary['discount'] ?? 0, // 只包含非优惠券的折扣
                'user_coupon_id' => $userCouponId,
                'receiver_name' => $address->name,
                'receiver_phone' => $address->phone,
                'receiver_address' => $address->full_address,
                'payment_method' => null, // 支付方式将在支付页面选择
                'payment_status' => Order::PAYMENT_PENDING,
                'notes' => $requestData['notes'] ?? null,
                'status' => 'pending',
            ]);

            // 创建订单项
            $product = Product::find($item['product_id']);
            $variant = $item['variant_id'] ? ProductVariant::find($item['variant_id']) : null;
            
            // 根据商品类型处理规格信息
            if ($product->product_type === 'single') {
                // 单规格商品，不设置变体信息和规格信息
                $order->items()->create([
                    'product_id' => $item['product_id'],
                    'variant_id' => null,
                    'sku' => $product->sku,
                    'product_name' => $item['name'],
                    'variant_name' => null,
                    'specifications' => null,
                    'price' => $item['price'],
                    'quantity' => $item['quantity'],
                    'total_amount' => $item['subtotal'],
                ]);
            } else {
                // 多规格商品，设置变体信息和规格信息
                $order->items()->create([
                    'product_id' => $item['product_id'],
                    'variant_id' => $item['variant_id'],
                    'sku' => $variant ? $variant->sku : $product->sku,
                    'product_name' => $item['name'],
                    'variant_name' => $variant ? $variant->name : null,
                    'specifications' => $item['specs'],
                    'price' => $item['price'],
                    'quantity' => $item['quantity'],
                    'total_amount' => $item['subtotal'],
                ]);
            }

            // 扣减库存
            $this->stockService->deductStock(
                $item['product_id'],
                $item['variant_id'] ?? null,
                $item['quantity']
            );

            // 使用优惠券
            if ($userCouponId && $couponDiscount > 0) {
                $this->couponService->useCoupon($userCouponId, $order->id, $couponDiscount);
            }

            Log::info('Order created from buy now', [
                'order_id' => $order->id,
                'order_number' => $order->order_number,
                'user_id' => $order->user_id,
                'total_amount' => $order->total_amount,
                'coupon_discount' => $couponDiscount,
            ]);

            return $order;
        });
    }

    /**
     * 从购物车创建订单
     * 
     * @param Cart $cart 购物车实例
     * @param UserAddress $address 收货地址
     * @param array $requestData 请求数据，包含notes等
     * @return Order 创建的订单实例
     * @throws \Exception 当库存不足或创建失败时抛出异常
     */
    public function createFromCart($cart, UserAddress $address, array $requestData): Order
    {
        return DB::transaction(function () use ($cart, $address, $requestData) {
            // 处理优惠券
            $couponDiscount = 0;
            $userCouponId = null;
            
            if (!empty($requestData['user_coupon_id'])) {
                $selectedItems = $cart->items->where('is_selected', true);
                $couponResult = $this->applyCoupon($requestData['user_coupon_id'], $cart->subtotal, $selectedItems->toArray());
                if ($couponResult['success']) {
                    $couponDiscount = $couponResult['discount'];
                    $userCouponId = $requestData['user_coupon_id'];
                }
            }

            // 创建订单
            $order = Order::create([
                'user_id' => auth()->id(),
                'order_number' => $this->orderNumberGenerator->generate(),
                'total_amount' => $cart->total_amount - $couponDiscount,
                'subtotal_amount' => $cart->subtotal,
                'shipping_fee' => $cart->shipping_fee,
                'discount_amount' => $cart->discount, // 只包含非优惠券的折扣
                'user_coupon_id' => $userCouponId,
                'receiver_name' => $address->name,
                'receiver_phone' => $address->phone,
                'receiver_address' => $address->full_address,
                'payment_method' => null, // 支付方式将在支付页面选择
                'payment_status' => Order::PAYMENT_PENDING,
                'notes' => $requestData['notes'] ?? null,
                'status' => 'pending',
            ]);

            // 准备商品数据
            $selectedItems = $cart->items->where('is_selected', true);
            $cartItems = $selectedItems->map(function ($item) {
                return [
                    'product_id' => $item->product_id,
                    'variant_id' => $item->variant_id,
                    'quantity' => $item->quantity,
                ];
            })->toArray();

            // 创建订单项
            foreach ($selectedItems as $item) {
                $variant = $item->variant;
                $product = $item->product;
                
                // 根据商品类型处理规格信息
                if ($product->product_type === 'single') {
                    // 单规格商品，不设置变体信息和规格信息
                    $order->items()->create([
                        'product_id' => $item->product_id,
                        'variant_id' => null,
                        'sku' => $product->sku,
                        'product_name' => $product->name,
                        'variant_name' => null,
                        'specifications' => null,
                        'price' => $item->price,
                        'quantity' => $item->quantity,
                        'total_amount' => $item->price * $item->quantity,
                    ]);
                } else {
                    // 多规格商品，设置变体信息和规格信息
                    $order->items()->create([
                        'product_id' => $item->product_id,
                        'variant_id' => $item->variant_id,
                        'sku' => $variant ? $variant->sku : $product->sku,
                        'product_name' => $product->name,
                        'variant_name' => $variant ? $variant->name : null,
                        'specifications' => $item->specifications,
                        'price' => $item->price,
                        'quantity' => $item->quantity,
                        'total_amount' => $item->price * $item->quantity,
                    ]);
                }
            }

            // 批量扣减库存
            $this->stockService->batchDeductStock($cartItems);

            Log::info('Order created from cart', [
                'order_id' => $order->id,
                'order_number' => $order->order_number,
                'user_id' => $order->user_id,
                'total_amount' => $order->total_amount,
                'items_count' => $selectedItems->count(),
            ]);

            return $order;
        });
    }

    /**
     * 处理订单支付
     */
    public function processPayment(Order $order, string $paymentMethod): array
    {
        if ($paymentMethod === 'cod') {
            // 货到付款，标记为货到付款确认状态
            $order->update([
                'payment_status' => 'cod_confirmed',
                'status' => 'processing',
                'paid_at' => now(),
            ]);

            Log::info('Order marked as COD confirmed', [
                'order_id' => $order->id,
                'order_number' => $order->order_number,
            ]);

            return [
                'success' => true,
                'redirect_url' => route('order.show', $order->order_number),
                'message' => '订单提交成功！货到付款订单已确认。'
            ];
        } else {
            // 在线支付，跳转到支付页面
            return [
                'success' => true,
                'redirect_url' => route('payment.show', $order->order_number),
                'message' => '订单创建成功，请完成支付。'
            ];
        }
    }

    /**
     * 取消订单
     */
    public function cancelOrder(Order $order, string $reason = null): void
    {
        DB::transaction(function () use ($order, $reason) {
            $order->cancel($reason);

            Log::info('Order cancelled', [
                'order_id' => $order->id,
                'order_number' => $order->order_number,
                'reason' => $reason,
                'user_id' => auth()->id(),
            ]);
        });
    }

    /**
     * 确认收货
     */
    public function confirmDelivery(Order $order): void
    {
        $order->markAsDelivered();

        Log::info('Order delivery confirmed', [
            'order_id' => $order->id,
            'order_number' => $order->order_number,
            'user_id' => auth()->id(),
        ]);
    }

    /**
     * 获取订单列表（支持筛选和搜索）
     */
    public function getOrdersForUser(int $userId, array $filters = []): \Illuminate\Contracts\Pagination\LengthAwarePaginator
    {
        $query = Order::forUser($userId)
            ->with([
                'items.product.images',
                'items.variant.images',
                'userCoupon.coupon'
            ]);
        
        // 状态筛选
        if (!empty($filters['status'])) {
            $query->where('status', $filters['status']);
        }
        
        // 关键词搜索（订单号或商品名称）
        if (!empty($filters['keyword'])) {
            $keyword = $filters['keyword'];
            $query->where(function ($q) use ($keyword) {
                $q->byOrderNumber($keyword)
                  ->orWhereHas('items', function ($itemQuery) use ($keyword) {
                      $itemQuery->where('product_name', 'like', "%{$keyword}%");
                  });
            });
        }
        
        return $query->orderBy('created_at', 'desc')->paginate(10)->withQueryString();
    }

    /**
     * 获取订单详情
     */
    public function getOrderDetails(string $orderNumber): Order
    {
        return Order::where('order_number', $orderNumber)
            ->with([
                'items.product.images',
                'items.variant.images',
                'userCoupon.coupon',
                'afterSalesRequests' => function ($query) {
                    $query->orderBy('created_at', 'desc');
                }
            ])
            ->firstOrFail();
    }

    /**
     * 验证地址权限
     */
    public function validateAddressPermission(UserAddress $address, int $userId): void
    {
        if ($address->user_id !== $userId) {
            throw new \Exception('无权使用此地址');
        }
    }

    /**
     * 验证订单权限
     */
    public function validateOrderPermission(Order $order, int $userId): void
    {
        if ($order->user_id !== $userId) {
            throw new \Exception('无权操作此订单');
        }
    }

    /**
     * 应用优惠券
     * 
     * @param int $userCouponId 用户优惠券ID
     * @param float $orderAmount 订单金额
     * @param array $items 订单商品
     * @return array ['success' => bool, 'discount' => float, 'message' => string]
     */
    protected function applyCoupon(int $userCouponId, float $orderAmount, array $items): array
    {
        return $this->couponService->calculateDiscount($userCouponId, $orderAmount, $items);
    }

    /**
     * 退回优惠券（订单取消时）
     * 
     * @param Order $order 订单实例
     */
    public function refundCoupon(Order $order): void
    {
        if ($order->user_coupon_id) {
            $this->couponService->refundCoupon($order->user_coupon_id);
        }
    }
}
